package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Substitutions;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;
import com.conversationboard.site.Site;

@WebServlet(name = "AdminAddSubstitutionControllerServlet", urlPatterns = "/Admin/AdminAddSubstitutionControllerServlet")
public class AdminAddSubstitutionControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6012264330741547647L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			String loginId = request.getParameter("loginid").trim();
			String ipAddress = request.getParameter("ipaddress").trim();
			String regularExpression = request.getParameter("regularexpression").trim();
			String substitution = request.getParameter("substitution").trim();

			if (loginId.length() == 0 || regularExpression.length() == 0 || substitution.length() == 0) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", "Please fill in all of the fields");
				dispatcher.forward(request, response);
				return;
			}

			if (ipAddress.length() == 0) {
				ipAddress = "**********";
			}

			/* Try to compile the pattern to make sure it's legal */
			Pattern.compile(regularExpression);

			Substitutions subs = Site.getSubstitutions();
			subs.addSubstitution(loginId, ipAddress, regularExpression, substitution);

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Pages/Admin/substitutions.jsp");

		} catch (EncryptionException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
